package com.heima.article.service.impl;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.freemarker.FreemarkerGenerator;
import com.heima.file.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVo;
import com.heima.model.wemedia.pojos.WmNews;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private FreemarkerGenerator freemarkerGenerator;
    @Autowired
    private MinIoTemplate minIoTemplate;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Autowired
    private CacheService cacheService;
    @Override
    public ResponseResult load(ArticleHomeDto dto) {
        //minBehotTime=2063
        //publish_time<minBehotTime
        //0.参数判空
        if (dto==null) {
            log.warn("参数为空");
            return ResponseResult.okResult("");
        }
        List<ApArticle> articles =apArticleMapper.loadArticle(dto,1);
        return ResponseResult.okResult(articles);
    }

    @Override
    public ResponseResult loadFromCache(ArticleHomeDto dto) {
        //0.参数判空
        if (dto==null) {
            log.warn("参数为空");
            return ResponseResult.okResult("");
        }
        //1.查询redis里是否有文章
        String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
        if (StringUtils.isEmpty(jsonStr)) {
            //1.1没有,还是调用过去load方法
            return load(dto);
        }
       //1.2有内容
        List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
        return ResponseResult.okResult(hotArticleVoList);
    }

    @Override
    public ResponseResult loadmore(ArticleHomeDto dto) {
        //publish_time<minBehotTime
        List<ApArticle> articles =apArticleMapper.loadArticle(dto,1);
        return ResponseResult.okResult(articles);
    }

    @Override
    public ResponseResult loadnew(ArticleHomeDto dto) {
        //publish_time>maxBehotTime
        List<ApArticle> articles =apArticleMapper.loadArticle(dto,2);
        return ResponseResult.okResult(articles);
    }

    @Override
    @Async//异步
    public void generate(Long articleId) {
        //1.查询ApArticleContent表,获得里面content数据
        LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApArticleContent::getArticleId,articleId);
        ApArticleContent apArticleContentcontent = apArticleContentMapper.selectOne(wrapper);
        if(apArticleContentcontent==null){
            log.warn("文章内容不存在");
            return;
        }
        //2.创建一个数据集合map,把上一个content数据赋值到map里的content字段上
        Map<String,Object> map =new HashMap<>(1);
        map.put("content",apArticleContentcontent.getContent());
        //3.调用Freemarker插件,生成HTML界面
        InputStream is = freemarkerGenerator.generate("article.ftl", map);
        //4.调用MinIO插件,上传HTML界面
        String url = minIoTemplate.uploadFile("", articleId + ".html", is, "html");

        ApArticle apArticle = apArticleMapper.selectById(articleId);
        if(apArticle==null){
            log.warn("文章为空");
            return;
        }
        //5.更新ApArticle,修改里面static_url字段
        apArticle.setStaticUrl(url);
        apArticleMapper.updateById(apArticle);

    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult saveArticle(ArticleDto dto) {
        //1.判空
        if (dto==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Long id = dto.getId();
        String content = dto.getContent();
        //组装article
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(dto,article);

        //2.判断新增还是修改
        if (id ==null) {
            //3新增
            //3.1新增article
            int articleInsertResult = apArticleMapper.insert(article);
            if(articleInsertResult<1){
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"文章新增失败");
            }
            //3.2新增articleConfig表
            ApArticleConfig articleConfig = new ApArticleConfig();
            articleConfig.setIsComment(true);
            articleConfig.setIsForward(true);
            articleConfig.setIsDelete(false);
            articleConfig.setIsDown(false);
            articleConfig.setId(article.getId());
            int configInsertResult = apArticleConfigMapper.insert(articleConfig);
            if(configInsertResult<1){
                log.warn("配置表新增失败");
                throw  new RuntimeException("配置表新增失败");
            }

            //3.3新增articleContent表
            ApArticleContent articleContent = new ApArticleContent();
            articleContent.setArticleId(article.getId());
            articleContent.setContent(content);
            int contentInsertResult = apArticleContentMapper.insert(articleContent);
            if(contentInsertResult<1){
                log.warn("内容表新增失败");
                throw  new RuntimeException("内容表新增失败");
            }

            //调用现成的方法,实现文章详情的生成和更新
            generate(article.getId());
            return ResponseResult.okResult(article.getId());

        }else {
            //4修改
            //4.1修改article表
            int articleUpdateResult = apArticleMapper.updateById(article);
            if(articleUpdateResult<1){
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"文章修改失败");
            }
            //4.2修改articleContent表
            ApArticleContent articleContent = new ApArticleContent();
            articleContent.setContent(content);
            LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApArticleContent::getArticleId,id);
            int contentUpdateResult = apArticleContentMapper.update(articleContent, wrapper);
            if(contentUpdateResult<1){
                log.warn("内容表修改失败");
                throw  new RuntimeException("内容表修改失败");
            }
            //调用详情生成
            generate(id);
            return ResponseResult.okResult(id);
        }
    }

    @Override
    public void sendIndexUpdate(ApArticle article,String content) {
        if(article==null||StringUtils.isBlank(content)){
            log.warn("入参不能为空");
            return;
        }
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(article,vo);
        vo.setContent(content);
        kafkaTemplate.send("es.index.update",JSON.toJSONString(vo));
    }


}
